package com.xiaoxu.intranetweb.mybatisplusSzappdb.controller.compete;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSONObject;

import java.net.URLEncoder;

import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.compete.CompeteBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.CompeteExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.CompetePdtAuthExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.TruckExcelEn;
import com.xiaoxu.intranetweb.util.PermissionCheck;
import com.xiaoxu.intranetweb.util.SzResult;
import com.xiaoxu.intranetweb.util.WebFunctionUtil;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.Future;

@RestController
@RequestMapping(value = "/compete")
public class CompeteController {
    @Autowired
    private CompeteBu competeBu;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private WebFunctionUtil webFunctionUtil;

    //查询竞争表控制层
    @PostMapping("/getCompete")
    public SzResult getCompete(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        String id = jsonObject.getString("id");
        String title = jsonObject.getString("title");
        String startTime = jsonObject.getString("startTime");
        String endTime = jsonObject.getString("endTime");
        String minBid = jsonObject.getString("minBid");
//    private LocalDateTime executeStartTime;
//    private LocalDateTime executeEndTime;

        String Status = jsonObject.getString("Status");
        String archived = jsonObject.getString("archived");
        String page = jsonObject.getString("page");
        String pageSize = jsonObject.getString("pageSize");
        String fileList = jsonObject.getString("fileList");
        String token = request.getHeader("Authorization");
        Object status1 = jsonObject.getObject("status", Object.class);
        String plantId = request.getHeader("Plant-Id");
        List status = null;
        if (status1 != null && !status1.equals("")) {
            if (!status1.equals(0)) {
                status = (List) jsonObject.get("status");
            } else {
                status = Collections.singletonList(0);
            }
        } else {
            status = null;
        }
        return competeBu.getCompete(page, pageSize, id, title, startTime, endTime, minBid, status, archived, token, plantId);
    }
    //   审批，就是将status变成10
    @PostMapping("approveCompete")
    public SzResult approveCompete(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        String id = jsonObject.getString("id");
        Integer status = jsonObject.getInteger("status");
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return competeBu.approveCompete(id, status,token,plantId);
    }
    //新增竞争表控制层
    @PostMapping("/addCompete")
    @PermissionCheck("compete_add")
    public SzResult addCompete(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        String title = jsonObject.getString("title");
        String beginDate = jsonObject.getString("beginDate");
        String beginTDate = jsonObject.getString("beginTDate");
        String executeStartTime = jsonObject.getString("executeStartTime");
        String executeEndTime = jsonObject.getString("executeEndTime");
        String content = jsonObject.getString("content");
        Integer bidType =  jsonObject.getInteger("bidType");
        String minBid = jsonObject.getString("minBid");
        String archived = jsonObject.getString("archived");
        String openMinBid = jsonObject.getString("openMinBid");
        Integer negativeBidding = jsonObject.getInteger("negativeBidding");
        String priceShow = jsonObject.getString("priceShow");
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return competeBu.addCompete(title, beginDate, beginTDate,executeStartTime,executeEndTime, content,bidType, minBid, archived, openMinBid, priceShow,negativeBidding, token, plantId);
    }

    //删除竞争表控制层
    @GetMapping("/deleteCompete")
    @PermissionCheck("compete_del")
    public SzResult deleteCompete(@RequestParam String id, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return competeBu.delCompete(id, token, plantId);
    }

    //修改竞争表控制层
    @PostMapping("/updateCompete")
    @PermissionCheck("compete_update")
    public SzResult updateCompete(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        String id = jsonObject.getString("id");
        String title = jsonObject.getString("title");
        String content = jsonObject.getString("content");
        Integer bidType =  jsonObject.getInteger("bidType");
        String beginDate = jsonObject.getString("beginDate");
        String executeStartTime = jsonObject.getString("executeStartTime");
        String executeEndTime = jsonObject.getString("executeEndTime");
        String beginTDate = jsonObject.getString("beginTDate");
        String minBid = jsonObject.getString("minBid");
        String status = jsonObject.getString("status");
        String openMinBid = jsonObject.getString("openMinBid");
        String priceShow = jsonObject.getString("priceShow");
        Integer negativeBidding = jsonObject.getInteger("negativeBidding");
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return competeBu.updateCompete(id, title, content,bidType, beginDate, beginTDate,executeStartTime,executeEndTime, minBid, status, openMinBid, priceShow,negativeBidding, token, plantId);
    }

    //    导出excel
    @PostMapping("/exportExcel")
    public void exportExcel(@RequestBody JSONObject jsonParam, HttpServletResponse response, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        //        实体类
        List<Map<String, Object>> fields = jsonParam.getObject("fields", List.class);
//        文件名使用utf-8编码
        String filename = jsonParam.getString("filename");
//        数据
        List<Map<String, Object>> ids = jsonParam.getObject("ids", List.class);
//        是否有表头
        Boolean isHeader = jsonParam.getBoolean("isHeader");
//        mode为"current"时，导出当前页，为"all"时，导出所有页，selected时，导出选中数据
        String mode = jsonParam.getString("mode");
//        是否原始数据
        Boolean original = jsonParam.getBoolean("original");
//        分页
        Map<String, String> pager = jsonParam.getObject("pager", Map.class);
//        表格标题
        String sheetName = jsonParam.getString("sheetName");
        Map form = jsonParam.getObject("form", Map.class);
        String title = Optional.ofNullable(form.get("title")).orElse("").toString();
        String startTime = Optional.ofNullable(form.get("startTime")).orElse("").toString();
        String endTime = Optional.ofNullable(form.get("endTime")).orElse("").toString();
        String minBid = Optional.ofNullable(form.get("minBid")).orElse("").toString();
        String Status = Optional.ofNullable(form.get("Status")).orElse("").toString();
        String archived = Optional.ofNullable(form.get("archived")).orElse("").toString();
        Future<List<CompeteExcelEn>> listFuture = competeBu.exportExcel(fields, filename, ids, isHeader, mode, original, pager, sheetName, token, title, startTime, endTime, minBid, Status, archived, plantId);
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        BorderStyle borderStyle = BorderStyle.THIN;
        short borderColor = IndexedColors.BLACK.getIndex();
        contentWriteCellStyle.setBorderTop(borderStyle);
        contentWriteCellStyle.setBorderBottom(borderStyle);
        contentWriteCellStyle.setBorderLeft(borderStyle);
        contentWriteCellStyle.setBorderRight(borderStyle);
        contentWriteCellStyle.setTopBorderColor(borderColor);
        contentWriteCellStyle.setBottomBorderColor(borderColor);
        contentWriteCellStyle.setLeftBorderColor(borderColor);
        contentWriteCellStyle.setRightBorderColor(borderColor);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(null, contentWriteCellStyle);
        List<CompeteExcelEn> competeExcelEns = listFuture.get();
        response.setContentType("application/vnd.ms-excel; charset=utf-8");
        response.setCharacterEncoding("utf-8");
        if (filename == null || filename.equals("")) {
            filename = "竞标信息";
        }
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8") + ".xlsx");
        EasyExcel.write(response.getOutputStream(), CompeteExcelEn.class).registerWriteHandler(horizontalCellStyleStrategy).sheet("竞标信息").doWrite(competeExcelEns);
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }


    /**
     * 开标按钮
     */
    @GetMapping("/openCompete")
    @PermissionCheck("compete_open")
    public SzResult openCompete(@RequestParam String id, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return competeBu.openCompete(id, token, plantId);
    }

    /**
     * 延时投标
     */
    @PostMapping("/delayedBid")
    @PermissionCheck("compete_delayed")
    public SzResult delayedBid(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        String id = jsonObject.getString("id");
        String delayedTime = jsonObject.getString("delayedTime");
        String token = request.getHeader("Authorization");
        String reason = jsonObject.getString("reason");
        String plantId = request.getHeader("Plant-Id");
        return competeBu.delayedBid(id, delayedTime, reason, token, plantId);
    }


    /**
     * 评标
     */
    @GetMapping("/evaluateBid")
    @PermissionCheck("compete_evaluate")
    public SzResult evaluateBid(@RequestParam String id, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return competeBu.evaluateBid(id, token, plantId);
    }

    /**
     * 定标
     */
    @GetMapping("/fixedBid")
    @PermissionCheck("compete_fixed")
    public SzResult fixedBid(@RequestParam String id, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return competeBu.fixedBid(id, token, plantId);
    }

    @GetMapping("/competepdtAuth")
    public SzResult getCompetePdtAuth(
            @RequestParam(value = "page", required = false) String page,
            @RequestParam(value = "pageSize", required = false) String pageSize,
            @RequestParam(value = "co", required = false) String co,
            @RequestParam(value = "chiCo", required = false) String chiCo,
            @RequestParam(value = "pdt", required = false) String pdt, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return competeBu.competePdtAuth(page, pageSize, co, chiCo, pdt, token, plantId);
    }


    //        删除授权品种
    @PostMapping("/competeDeletePdtAuth")
    @PermissionCheck("compete_deletePdtAuth")
    public SzResult competeDeletePdtAuth(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        String id = jsonObject.getString("id");//授权品种id
        return competeBu.deleteCompetePdtAuth(id, token, plantId);
    }

    /**
     * 新增竞标品种授权
     */
    @PostMapping("/addCompetePdtAuth")
    @PermissionCheck("compete_addPdtAuth")
    public SzResult addCompetePdtAuth(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        String pdtsauthPdt = jsonObject.getString("pdtsauthPdt");//授权品种
        String pdtsauthPrice = jsonObject.getString("pdtsauthPrice");//授权价格
        String pdtsauthCo = jsonObject.getString("pdtsauthCo");//授权单位
        String pdtsauthChico = jsonObject.getString("pdtsauthChico");//授权单位子单位
        return competeBu.addCompetePdtAuth(pdtsauthCo, pdtsauthChico, pdtsauthPdt, pdtsauthPrice, token, plantId);
    }

    /**
     * 冻结竞标品种授权
     */
    @PostMapping("/freezeCompetePdtAuth")
    @PermissionCheck("compete_freezePdtAuth")
    public SzResult freezePdtAuth(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        String id = jsonObject.getString("id");//授权品种id
        Integer lock = jsonObject.getInteger("lock");//授权品种状态
        return competeBu.freezePdtAuth(id, lock, token, plantId);
    }
    /**
     * 竞标品种授权导表
     */
    @PostMapping("/competePdtAuthExportExcel")
    public void pdtAuthExportExcel(@RequestBody JSONObject jsonParam, HttpServletResponse response, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
//        String plantId = null;
//        if (token != null) {
//            plantId = userInfoDao.getUserFactory(StpUtil.getLoginIdByToken(token).toString()).getId();
//        }
        List<Map<String, Object>> fields = jsonParam.getObject("fields", List.class);
        String filename = jsonParam.getString("filename");
        List<Map<String, Object>> ids = jsonParam.getObject("ids", List.class);
        boolean isHeader = jsonParam.getBoolean("isHeader");
        String mode = jsonParam.getString("mode");
        Boolean original = jsonParam.getBoolean("original");
        Map<String, String> pager = jsonParam.getObject("pager", Map.class);
        String sheetName = jsonParam.getString("sheetName");
        Map<String, String> form = jsonParam.getObject("form", Map.class);
        String pdtsauthCo = null;//授权单位
        String pdtsauthPdt = null;//授权品种
        if (form.get("pdtsauthCo") != null && !form.get("pdtsauthCo").equals("null")) {
            pdtsauthCo = form.get("pdtsauthCo").toString();
        }
        if (form.get("pdtsauthPdt") != null && !form.get("pdtsauthPdt").equals("null")) {
            pdtsauthPdt = form.get("pdtsauthPdt").toString();
        }
        Future<List<CompetePdtAuthExcelEn>> listFuture = competeBu.competePdtAuthExportExcel(fields, filename, ids, isHeader, mode, original, pager, sheetName, plantId, pdtsauthCo, pdtsauthPdt);
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        BorderStyle borderStyle = BorderStyle.THIN;
        short borderColor = IndexedColors.BLACK.getIndex();
        contentWriteCellStyle.setBorderTop(borderStyle);
        contentWriteCellStyle.setBorderBottom(borderStyle);
        contentWriteCellStyle.setBorderLeft(borderStyle);
        contentWriteCellStyle.setBorderRight(borderStyle);
        contentWriteCellStyle.setTopBorderColor(borderColor);
        contentWriteCellStyle.setBottomBorderColor(borderColor);
        contentWriteCellStyle.setLeftBorderColor(borderColor);
        contentWriteCellStyle.setRightBorderColor(borderColor);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(null, contentWriteCellStyle);
        List<CompetePdtAuthExcelEn> pdtAuthExcelEn = listFuture.get();
        response.setContentType("application/vnd.ms-excel; charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8") + ".xlsx");
        EasyExcel.write(response.getOutputStream(), CompetePdtAuthExcelEn.class)
                .registerWriteHandler(horizontalCellStyleStrategy)
                .sheet("竞标品种授权")
                .doWrite(pdtAuthExcelEn);
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }
}
